package com.lhd._05weibo.common.exception;

import com.lhd._05weibo.common.response.JsonResult;
import com.lhd._05weibo.common.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import springfox.documentation.spring.web.json.Json;

import javax.validation.ConstraintViolationException;

/**
 * @author lhd
 * @date 2024/4/26
 * @apiNote
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * ExceptionHandler注解：标识此方法为异常处理方法
     * 前提：控制器中抛出了异常
     * 1.首先查看是否定义全局异常处理器;
     * 2.已定义,则在类中定位处理该异常的异常处理方法;
     * 3.如果未定义,则定位该异常父类异常的异常处理方法;
     * 4.如果父类也未定义,则找能处理所有异常的Throwable方法;
     * 5.如果也未找到,则使用Spring MVC默认的异常处理机制[不友好];
     */
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex){
        /*
            ex.getMessage()方法：获取异常提示消息;
         */
        log.error("IllegalArgumentException = " + ex.getMessage());
        // {"state": 2002, "message": "操作失败", "data": "ID值不能小于0"}
        return new JsonResult(StatusCode.OPERATION_FAILED, ex.getMessage());
    }

//    @ExceptionHandler
//    public JsonResult doHandleRuntimeException(RuntimeException ex){
//        log.error("RuntimeException = " + ex.getMessage());
//
//        return new JsonResult(StatusCode.OPERATION_FAILED,ex.getMessage());
//    }

    /**
     * Validation验证框架异常:DTO类方式数据校验
     * 获取异常提示消息:ex.getFieldError().getDefaultMessage();
     */
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        log.error("Throwable = " + ex.getMessage());

        return new JsonResult(StatusCode.VALIDATED_ERROR,ex.getFieldError().getDefaultMessage());
    }

    @ExceptionHandler
    public JsonResult doHandle(ConstraintViolationException ex){
        log.error("message = " + ex.getMessage());
        String message = ex.getMessage().split(":")[1].trim();

        return new JsonResult(StatusCode.VALIDATED_ERROR, message);
    }

    //    @ExceptionHandler
//    public JsonResult doThrowableException(Throwable ex){
//        log.error("Throwable = " + ex.getMessage());
//
//        return new JsonResult(StatusCode.THROWABLE_ERROR,ex.getMessage());
//    }
}
